package com.zj.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zj.restApi.OrderApi;
import com.zj.restApi.ProductApi;
import com.zj.web.bean.*;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log
public class OrderToolService {
    @Autowired
    private OrderApi orderApi;
    @Autowired
    private ProductApi productApi;

    /**
     * 查找默认地址
     */
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class findDefaultAddressResponse {
        @JsonProperty("data")
        public List<AddressDTO> data;
    }
    @Tool("查找默认地址")
    public String findDefaultAddress(@P("用户ID") Long memoryId) {
        try {
            ResponseEntity<ResponseResult> responseEntity = orderApi.getDefaultAddress(1, memoryId);
            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，地址服务暂时不可用，请稍后重试。";
            }
            ResponseResult responseResult = responseEntity.getBody();
            if (responseResult.getCode() != 1) {
                return "抱歉，没有找到默认地址。";
            }
            Object data = responseResult.getData();
            ObjectMapper objectMapper = new ObjectMapper();
            AddressDTO address = objectMapper.convertValue(data, AddressDTO.class);

            if (address == null) {
                return "抱歉，没有找到默认地址。";
            }
            return "默认地址ID " + address.getAddressId();
        } catch (Exception e) {
            return "查找默认地址失败: " + e.getMessage();
        }
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class OrderSearchResponse {
        @JsonProperty("data")
        public List<ProductDTO> data;
    }
    @Tool("用户下单商品，需要依次提供：用户ID（即memoryId）、收货地址ID、商品ID、购买数量。请确保所有参数完整。")
    public String addOrderByAI(@P("用户ID") Long memoryId,
                               @P("地址ID") Long addressId,
                               @P("商品id") Long productId,
                               @P("数量") Integer quantity) {
        try {
            log.info("开始下单，用户id: " + memoryId + ", 地址id: " + addressId );
            //开始下单
            // 调用订单服务的下单接口
            ResponseEntity<ResponseResult> responseEntity1 = orderApi.addOrderByAI(memoryId,addressId);

            if (responseEntity1.getStatusCode() != HttpStatus.OK || responseEntity1.getBody() == null) {
                return "抱歉，订单服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity1.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，下单失败，状态码: " + responseResult.getCode() + "，消息: " + responseResult.getMsg();
            }

//            // 修复LinkedHashMap到ProductDTO的转换问题
//            // ProductDTO product = (ProductDTO) responseResult.getData();

            Object data = responseResult.getData();
            System.out.println("下单成功，订单ID: " + data);
            ObjectMapper objectMapper = new ObjectMapper();
            OrderMessageDTO order = objectMapper.convertValue(data, OrderMessageDTO.class);
            log.info("下单成功，订单ID: " + order.getOrderId());


            // 新增订单ID校验
            if (order.getOrderId() == null || order.getOrderId() <= 0) {
                return "订单创建失败：未获取到有效订单ID";
            }

            //根据商品id查询商品详情
            ResponseEntity<ResponseResult> responseEntity2 = productApi.getProductDetailById(productId);
            if (responseEntity2.getStatusCode() != HttpStatus.OK || responseEntity2.getBody() == null) {
                return "抱歉，商品服务暂时不可用，请稍后重试。";
            }
            ResponseResult responseResult2 = responseEntity2.getBody();
            if (responseResult2.getCode() != 1) {
                return "抱歉，没有找到ID为 " + productId + " 的商品。";
            }
            //将商品详情转换为OrderdetailDTO
            ObjectMapper objectMapper1 = new ObjectMapper();
            ProductDTO product = objectMapper1.convertValue(responseResult2.getData(), ProductDTO.class);
            log.info("下单商品详情: " + product);

            //添加订单详情
            ResponseEntity<ResponseResult> responseEntity3 = orderApi.addDetails(order.getOrderId(), List.of(new OrderdetailDTO(productId, quantity, product.getPrice())));
            if (responseEntity3.getStatusCode() != HttpStatus.OK || responseEntity3.getBody() == null) {
                return "抱歉，订单详情服务暂时不可用，请稍后重试。";
            }
            ResponseResult responseResult3 = responseEntity3.getBody();
            if (responseResult3.getCode() != 1) {
                return "抱歉，添加订单详情失败，状态码: " + responseResult3.getCode() + "，消息: " + responseResult3.getMsg();
            }
            //加入订单详情进入数据库的返回值是boolean类型
            boolean success = (boolean) responseResult3.getData();
            if (!success) {
                return "抱歉，添加订单详情失败，状态码: " + responseResult3.getCode() + "，消息: " + responseResult3.getMsg();
            }
//            //将商品详情转换为OrderdetailDTO
//            ObjectMapper objectMapper2 = new ObjectMapper();
//            OrderdetailDTO orderdetail = objectMapper2.convertValue(responseResult3.getData(), OrderdetailDTO.class);
//            log.info("下单商品详情: " + orderdetail);

            return String.format("""
                    🎉 订单创建成功！
                    
                    📦 订单号：%s
                    📍 收货地址ID：%s
                    
                    请及时完成支付，祝您购物愉快！
                    """,
                    order.getOrderId()!=null?order.getOrderId().toString():"N/A",
                    addressId != null ? addressId.toString() : "N/A");
        } catch (Exception e) {
            log.severe("下单失败，异常信息: " + e.getMessage());
            return "下单失败，异常信息: " + e.getMessage();
        }
    }

    @Tool("查询订单状态，当用户问'我的订单支付成功了吗'、'订单状态'等问题时使用。需要用户提供订单ID，如果用户未提供，先询问获取订单ID。")
    public String findOrderStatusById(@P("订单ID") Long orderId) {
        try {
            ResponseEntity<ResponseResult> responseEntity = orderApi.findOrderStatusById(orderId);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，订单状态查询服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "查询订单状态失败: " + responseResult.getMsg();
            }

            Integer orderStatus = (Integer) responseResult.getData();
            if (orderStatus == null) {
                return "订单不存在";
            }

            // 映射订单状态到用户友好的描述
            String statusDescription = switch (orderStatus) {
                case 0 -> "未支付";
                case 1 -> "待发货";
                case 2 -> "待收货";
                case 3 -> "已完成";
                default -> "未知订单状态";
            };

            return String.format("订单状态: %s", statusDescription);
        } catch (Exception e) {
            log.severe("查询订单状态失败，异常信息: " + e.getMessage());
            return "查询订单状态失败，异常信息: " + e.getMessage();
        }
    }
    @Tool("当用户提及“支付订单”“我要付款”“结算订单”等支付意图时触发。自动从对话上下文提取订单ID、支付金额、邮箱地址，无需重复询问用户。生成支付宝支付链接并返回可点击链接。")
    public String payOrderWithLink(@P("订单ID") Long orderId,
                                   @P("支付金额") String totalAmount) {
        try {
            log.info("生成支付链接，订单ID: " + orderId + ", 金额: " + totalAmount);

            ResponseEntity<ResponseResult> responseEntity = orderApi.createOrder(orderId, totalAmount, null);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，支付服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "支付订单创建失败: " + responseResult.getMsg();
            }

            Object data = responseResult.getData();
//            String paymentForm = safelyConvertToString(data);

            if (data == null) {
                return "支付订单创建成功，但未获取到支付表单。";
            }

            // 从支付表单中提取支付URL（需要根据支付宝返回的HTML表单解析）
            String paymentUrl = extractPaymentUrlFromForm(data.toString());

            if (paymentUrl != null) {
                // 生成可点击的Markdown格式链接
                return generateClickablePaymentLink(orderId, totalAmount, paymentUrl);
            } else {
                // 如果无法提取URL，返回表单内容（简化版）
                return String.format("""
                💳 支付订单创建成功！
                
                📦 订单号：%d
                💰 支付金额：%s元
                
                请复制以下链接到浏览器完成支付：
                %s
                
                或者扫描二维码完成支付。
                """, orderId, totalAmount, data);
            }

        } catch (Exception e) {
            log.severe("生成支付链接时出现错误: " + e.getMessage());
            return "支付链接生成失败: " + e.getMessage();
        }
    }

    /**
     * 从支付宝表单中提取支付URL
     */
    private String extractPaymentUrlFromForm(String paymentForm) {
        try {
            // 支付宝表单通常包含类似这样的结构：
            // <form action="https://openapi.alipay.com/gateway.do" ...>
            if (paymentForm.contains("form action=")) {
                // 简单的HTML解析，提取action属性
                int startIndex = paymentForm.indexOf("action=\"") + 8;
                int endIndex = paymentForm.indexOf("\"", startIndex);
                if (startIndex > 7 && endIndex > startIndex) {
                    return paymentForm.substring(startIndex, endIndex);
                }
            }

            // 如果是直接返回的支付URL
            if (paymentForm.startsWith("http")) {
                return paymentForm;
            }

            return null;
        } catch (Exception e) {
            log.warning("提取支付URL失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 生成可点击的支付链接（Markdown格式）
     */
    private String generateClickablePaymentLink(Long orderId, String amount, String paymentUrl) {
        // 对URL进行编码处理
        String encodedUrl = paymentUrl.replace("\"", "").trim();

        return String.format("""
        🎯 订单支付准备就绪！
        
        📦 订单号：`%d`
        💰 支付金额：**%s元**
        
        ⚡ [点击这里立即支付](%s)
        
        💡 **支付说明：**
        - 点击上方链接跳转到支付宝支付页面
        - 支付完成后系统会自动更新订单状态
        - 如有问题请联系客服
        
        🔒 支付链接：`%s`
        """, orderId, amount, encodedUrl, encodedUrl);
    }

    /**
     * 生成HTML格式的支付链接（如果前端支持HTML渲染）
     */
    private String generateHTMLPaymentLink(Long orderId, String amount, String paymentUrl) {
        String encodedUrl = paymentUrl.replace("\"", "").trim();

        return String.format("""
        <div style="border: 1px solid #e1e1e1; padding: 15px; border-radius: 8px; background: #f9f9f9;">
            <h3 style="color: #1890ff;">💳 订单支付</h3>
            <p><strong>订单号：</strong>%d</p>
            <p><strong>支付金额：</strong><span style="color: #f5222d; font-size: 18px;">%s元</span></p>
            <a href="%s" target="_blank" style="display: inline-block; padding: 10px 20px; 
               background: #1890ff; color: white; text-decoration: none; border-radius: 4px; 
               margin: 10px 0;">
               ⚡ 立即支付
            </a>
            <p style="font-size: 12px; color: #666;">支付链接：%s</p>
        </div>
        """, orderId, amount, encodedUrl, encodedUrl);
    }
}
